/*
 * This class will be called when user will select particular variable from the history page.
 *  
 */
package com.fipl.taksar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.artfulbits.aiCharts.ChartView;
import com.artfulbits.aiCharts.Base.ChartArea;
import com.artfulbits.aiCharts.Base.ChartPoint;
import com.artfulbits.aiCharts.Base.ChartSeries;
import com.artfulbits.aiCharts.Base.ChartAxis.LabelsMode;
import com.artfulbits.aiCharts.Types.ChartTypes;
import com.fipl.parse.DayParseVariable;
import com.fipl.parse.HistoricalParser;

@SuppressWarnings("unchecked")
public class ShowGraph extends Activity {

	private boolean noDataFlag = false;
	private int index = 0;
	private Runnable thread;
	private String variableSelect;
	private String dbName;
	private String year;
	private String month;
	private String day;
	private String noOfDays;
	private Button refreshButton;
	private Button bookmarkButton;
	private Button hourlyButton;
	private LinearLayout linearLayout;
	private ProgressDialog progressDialog;	
	private HistoricalParser parser;
	private ArrayList<Double>[] timeinterval = new ArrayList[12];
	private ArrayList<String> mapData = new ArrayList<String>();
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.configure);
		
		dbName = ((GlobalData)this.getApplicationContext()).getDbName();
		Bundle bundle = getIntent().getExtras();
		year = bundle.getString("year");				// will get year value from the previous activity
		month = bundle.getString("month");				// will get month value from the previous activity
		day = bundle.getString("day");					// will get day value from the previous activity
		noOfDays = bundle.getString("noofdays");		// will get no of days value from the previous activity	
		index = bundle.getInt("variableIndex");			// will get index value from the previous activity
		variableSelect = bundle.getString("variable");	// will get variable select value from the previous activity

		callDialog();					// call the loader to get data from the url

	}
	
	/*
	 * This will be called when hourly button is pressed and this will show data of particular variable with two hours interval
	 * for particular two hour eight data will be shown.
	 */
	public void HourlyGraph(){
		
		if(noDataFlag){
			getError();
		}else{
			setContentView(R.layout.timeinterval);
			String [] pointLable = {"0-2","2-4","4-6","6-8","8-10","10-12","12-14","14-16","16-18","18-20","20-22","22-24"};
			ChartPoint point = null;
			
			ChartView chartView = (ChartView)findViewById(R.id.chartView);
			ChartSeries seriesNew = chartView.getSeries().get(0);
			seriesNew.setShowLabel(true);
			for(int l=0; l<12;l++){
				for(int k=0; k<8;k++){
					point = seriesNew.getPoints().addXY(l,timeinterval[l].get(k));
					point.setAxisLabel(pointLable[l]);
				}
			}
			ChartArea area = chartView.getAreas().get(0);
			area.getDefaultXAxis().setLabelsMode(LabelsMode.SeriesLabels);	
			
			ChartSeries[] series = new ChartSeries[pointLable.length];
			for(int i = 1; i<pointLable.length;i++){
				series[i] = new ChartSeries(ChartTypes.Point);
				series[i].setName(pointLable[i]);
				series[i].setShowLabel(true);
				for(int j=0;j<8;j++){
					point = series[i].getPoints().addXY(i,timeinterval[i].get(j));	
					point.setAxisLabel(pointLable[i]);
				}
				chartView.getSeries().add(series[i]);
			}
		}
	}
	
	/*
	 * This will show loading dialog on the screen
	 */
	public void callDialog(){

		this.progressDialog = ProgressDialog.show(ShowGraph.this,"Please wait", "Connecting.. Please wait..", true);

		new Thread(new Runnable(){
			public void run(){
				try{
					Thread.sleep(5000);
				}catch (Exception e){
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ShowGraph.this.progressDialog.dismiss();
				ShowGraph.this.handler.sendEmptyMessage(0);
			}

		}).start();

	}

	/*
	 * This method will be called first after the call dialog is finished.
	 * this will show data for the single variable. 
	 */
	public void getData(){

		setContentView(R.layout.singlevariable);

		refreshButton = (Button)findViewById(R.id.timeRefresh);
		bookmarkButton = (Button)findViewById(R.id.timeBookmark);
		hourlyButton = (Button)findViewById(R.id.timeInterval);
		hourlyButton.setText("Hourly Chart");

		linearLayout = (LinearLayout)findViewById(R.id.threeBtn);
		linearLayout.removeView(refreshButton);
		linearLayout.removeView(bookmarkButton);

		ChartSeries series;
		ArrayList<String> fetcha = new ArrayList<String>();
		
		if(month.length()==0 | year.length()==0 | day.length()==0){
			Date date = new Date();
			month = String.valueOf((date.getMonth())+1);
			year = String.valueOf(date.getYear()+1900);
			day = String.valueOf(date.getDate());
		}

		parser= new HistoricalParser(dbName,year,month,day,noOfDays,variableSelect);
		if(parser.SelectVariableData() == -1){
			getError();
		}else{
			//Solo ocupa los campos fecha y average de la variable
			mapData.addAll(parser.selectVariableParse.average);
			fetcha.addAll(parser.selectVariableParse.fecha);
		}

		Date[] fetchaStr = new Date[fetcha.size()];
		try{
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			for(int i = 0; i<fetcha.size();i++){
				fetchaStr[i]=dateFormat.parse(fetcha.get(i));
			}
		}catch (Exception e) {
			// TODO: handle exception
			Log.d("System out", "Error date "+e.getMessage());
		}

		ChartView chartView = (ChartView)findViewById(R.id.chartView);
		series = chartView.getSeries().get(0);
		series.setShowLabel(true);
		series.setLegend(variableSelect);
		for(int i=0; i<mapData.size();i++){
			ChartPoint point = series.getPoints().addXY(i,Double.parseDouble(mapData.get(i)));
			point.setAxisLabel(fetchaStr[i].getDate()+"/"+(fetchaStr[i].getMonth()+1)+"/"+(fetchaStr[i].getYear()+1900));	
		}
		ChartArea area = chartView.getAreas().get(0);
		area.getDefaultXAxis().setLabelsMode(LabelsMode.SeriesLabels);
		
		hourlyButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				thread = new Runnable() {
					public void run() {
						// TODO Auto-generated method stub
						getHourly();
					}
				};
				Thread t = new Thread(null, thread, "getData");
				t.start();
				progressDialog = ProgressDialog.show(ShowGraph.this, "Please Wait...", "Retrieving Data...",true);
			}
			
		});

	}

	public void getHourly(){
		DayParseVariable dayParseVariable ;
		int j =0;
		Log.d("System out","database name in graph ");
		for(int i=2;i<=24;i=i+2){
			String interval = String.valueOf(i-2)+"-"+ String.valueOf(i);
			String date = year+"-"+month+"-"+day;
			dayParseVariable = new DayParseVariable(dbName,date,interval);
			if(dayParseVariable.parseData()!= -1){
				timeinterval[j] = new ArrayList<Double>();
				timeinterval[j].addAll(dayParseVariable.parserVariable.arraylistMap.get(index));
			}else{
				noDataFlag = true;
				break;
			}
			j++;
		}
		handler2.sendEmptyMessage(0);
	}

	public void getError(){

		AlertDialog.Builder builder = new AlertDialog.Builder(ShowGraph.this);
		if(noDataFlag){
			builder.setMessage("No hourly data available for this variable!");
		}else{
			builder.setMessage("No Data Available!");
		}
		
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		builder.show();
	}

	Handler handler2 = new Handler(){
		@Override
		public void handleMessage(Message msg){
			progressDialog.dismiss();
			HourlyGraph();
		}
	};

	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			progressDialog.dismiss();
			getData();
		}
	};
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	public void onStop(){
		super.onStop();
		ShowGraph.this.finish();
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event){
		super.onKeyDown(keyCode, event);
		
		if(keyCode == KeyEvent.KEYCODE_BACK){
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), HistoricalActivity.class);
			startActivity(intent);
		}
		return false;
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu (Menu menu){
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.option, menu);
		return true;
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem menuItem){
		
		switch (menuItem.getItemId()) {
		
		case R.id.menuDb:
			((GlobalData)this.getApplicationContext()).setLoginFlag(false);
			((GlobalData)this.getApplicationContext()).setMenuNo(100);
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), ConfigurationActivity.class);
			startActivity(intent);
			break;
		
		case R.id.menuExit:
			ShowGraph.this.finish();
			break;
		
		}
		return true;
	}
	
}